#include "PointDevice.h"
#include "Main/GateWay.h"
PointDevice::PointDevice(QObject *parent) :
    BaseInterface<PointDevice>(parent)
{
    qDebug()<<"PointDevice running-1";
    m_pInstance = this;
    pointProtocol = new PointProtocol(this);
    this->registerProtocol(pointProtocol);

    DelaySendTimer = new QTimer(this);
    DelaySendTimer->setInterval(100);
    connect(DelaySendTimer, SIGNAL(timeout()), this, SLOT(DelaySendSlot()));
    DelaySendTimer->start();


    registerCmdHandler(ControlPointCmd::FunctionCode,ControlPointCmd::staticMetaObject, &PointDevice::controlPointCmdHandle);
    registerFuncHandler(ControlPointFunc::FunctionCode, &PointDevice::controlPointFuncHandle);
       qDebug()<<"PointDevice running-2";
}


void PointDevice::controlPointCmdHandle(PortStruct source,QSharedPointer<BaseCmd> sharedCmd)
{
    Q_UNUSED(source);
    ControlPointCmd *setControlPointCmd = qobject_cast<ControlPointCmd*>(sharedCmd.data());

    int address = setControlPointCmd->address();
    int value = setControlPointCmd->value();
    ControlPointFunc *pointControlFunc = new ControlPointFunc();
    ControlPointStruct sourcePoint;
    sourcePoint.setAddress(address);
    sourcePoint.setValue(value);
    PortStruct target;
    foreach (const BasePort *port , m_portList)
    {
         if((port->portParam().type() == "UART" && port->portParam().name() == "RS485"))
         {
             target = port->portParam();
         }
    }
 //   sourcePoint.setPortStruct(target);

    SavePointXml *savePointXml =SavePointXml::getInstance();

    savePointXml->SavePointData(address,value);
    QString stata="Read-RS485";
    savePointXml->JoinSystemList(address,value,stata);
  /* if((address==1)&&(value==1))
        sendHttp("123");
   else if((address==1)&&(value==2))
        sendHttpFile("123");
    else if((address==1)&&(value==3))
         sendHttpCreate("123");
   else if((address==1)&&(value==4))
        sendHttpIdentifi("123");
    else if((address==1)&&(value==5))
         sendHttpResult("123");*/
    QList<ControlPointStruct> sourcePointList;
    sourcePointList.append(sourcePoint);
    pointControlFunc->setSourceDevice(this->name());
    pointControlFunc->setSourcePointList(sourcePointList);
    QSharedPointer<BaseFunc> sharedPointControlFunc(pointControlFunc);
    emit transferFuncSignal(sharedPointControlFunc);
    OtherEquipmentXml *otherEquipmentXml = OtherEquipmentXml::getInstance();
    Function(otherEquipmentXml->m_pointSwitchUdpList,address,value);
}


void PointDevice::controlPointFuncHandle(QSharedPointer<BaseFunc> sharedFunc)
{

    ControlPointFunc *pointControlFunc = qobject_cast<ControlPointFunc*>(sharedFunc.data());
    QList<ControlPointStruct> controlPointList;


    qDebug()<<"[PointDevice::controlPointFuncHandle]"<<pointControlFunc->sourceDevice()<<" "<<this->name();
    if(pointControlFunc->sourceDevice() != this->name())
    {
        controlPointList.append(pointControlFunc->sourcePointList());
    }
    controlPointList.append(pointControlFunc->controlPointList());


    printf("[PointDevice::controlPointFuncHandle]---controlPointList size is %d\r\n",controlPointList.size());
    //printf("controlPointList add value is %d  %d\r\n",controlPointList.at(0).address(),controlPointList.at(0).value());
   // printf("controlPointList add value is %d  %d\r\n",controlPointList.at(1).address(),controlPointList.at(1).value());

    if(controlPointList.isEmpty())
    {
        return;
    }


    PortStruct target;
    foreach (const BasePort *port , m_portList)
    {
         if((port->portParam().type() == "UART" && port->portParam().name() == "RS485"))
         {
             target = port->portParam();
         }
    }
    //if(controlPointList.size()>0)
    //    qDebug()<<"controlPointFuncHandle controlPointList.size()="<<controlPointList.size();
    for(int i=0; i<controlPointList.size(); i++)
    {

        ControlPointStruct controlPoint = controlPointList.at(i);
        int address = controlPoint.address();
        int value = controlPoint.value();
        quint64 getDelayTime=controlPoint.delayTime();
        QList <QString>ControlPortlist=controlPoint.Portlist();
        bool RightPort=false;
        foreach(const QString &PortType, ControlPortlist)
        {
            if(PortType=="RS485")
            {
                RightPort=true;
            }
       //     qDebug()<<"PostType="<<PostType;
        }
     //   qDebug()<<"ControlPortlist.size="<<QString::number(controlPoint.Portlist().size());
        if(ControlPortlist.size()==0||RightPort==true)
        {
     //       qDebug()<<"true send data";
            if(getDelayTime==0)
            {
                qDebug()<<"Time is zero now--"<<controlPoint.address()<<"  "<<controlPoint.value();
                if((controlPoint.address()>0)||(controlPoint.value()>0))
                {
                ControlPointCmd *setControlPointCmd = new ControlPointCmd();

                setControlPointCmd->setAddress(address);
                setControlPointCmd->setValue(value);

                QSharedPointer<BaseCmd> sharedSetControlPointCmd(setControlPointCmd);

                 SavePointXml *savePointXml =SavePointXml::getInstance();

                 savePointXml->SavePointData(address,value);
                 QString stata="Write-RS485";
                 savePointXml->JoinSystemList(address,value,stata);

                sendCmd(target,sharedSetControlPointCmd);
                }
                else
                {
                        if(controlPoint.thirdFuncLen() > 0)
                     emit sendDataSignal(target,controlPoint.thirdFuncList());
                }
            }else
            {
                qDebug()<<"[PointDevice.cpp:controlPointFuncHandle]joinDelayTime---"<<controlPoint.address()<<"  "<<controlPoint.value();
              //  controlPoint.setPortStruct(target);
                SceneListXml *sceneListXml = SceneListXml::getInstance();
              sceneListXml->joinDelayTimeList(controlPoint);
            }
        }

    }
}

void PointDevice::senddata(QByteArray data)
{
    PortStruct target;
    target.setType("UART");
    target.setName("RS485");

    qDebug()<<"point";
    sendDataSignal(target,data);
}

bool PointDevice::Function(QList<PointSwitchUdpStruct> list,quint16 addr,quint16 value)
{
    pointProtocol = new PointProtocol(this);
    //qDebug()<<"now in function";
    foreach (const PointSwitchUdpStruct &pointSwitchUdpStruct, list)
    {
        quint16 getAddr =pointSwitchUdpStruct.Addr();
        QString getIP   =pointSwitchUdpStruct.IP();
        PortStruct target;
        target.setType("UDP");
        target.setName("NetPointDeviceUDP");
        target.setIp(getIP);
        target.setPort(20000);
        if(getAddr == addr)
        {
            PortStruct m_source;
            m_source.setIp(getIP);
            quint16 function=0x0f80;
            QByteArray data = pointProtocol->getPointData(function,addr,value);
            sendDataSignal(target,data);

        }
    }
    return true;
}
void PointDevice::DelaySendSlot()
{
   // qDebug()<<"DelaySendSlot hello";
    static int num=0;
    num++;
    SceneListXml *sceneListXml = SceneListXml::getInstance();
    QList<ControlPointStruct>DelaySendList;
    DelaySendList=sceneListXml->getDelayTimeList();
    int i;
  //  if(DelaySendList.size() > 0)
 //       qDebug()<<"[PointDevice::DelaySendSlot] DelaySendList.size()=="<<DelaySendList.size();
    for(i=0;i<DelaySendList.size();i++)
    {

        ControlPointStruct Struct=DelaySendList.at(i);

        quint64 structDelayTime=Struct.delayTime();
        // qDebug()<<"DelaySendSlot i="<<i<<" "<<Struct.address()<<" "<<Struct.value()<<" "<<structDelayTime;
        QList <QString>ControlPortlist=Struct.Portlist();
        bool RS485Port=false;
        bool ZigbeePort=false;
        foreach(const QString &PostType, ControlPortlist)
        {
            if(PostType=="RS485")
            {
                RS485Port=true;
            }
            if(PostType=="ZIGBEE")
            {
                ZigbeePort=true;
            }
           // qDebug()<<"DelaySendSlot PostType="<<PostType;
        }

        if(structDelayTime>0)
        {
            Struct.setDelayTime(structDelayTime-1);
            DelaySendList.replace(i,Struct);
        }
        else
        {
           // qDebug()<<"structDelayTime==0";
            int address = Struct.address();
            int value = Struct.value();

            ControlPointCmd *setControlPointCmd = new ControlPointCmd();
            setControlPointCmd->setAddress(address);
            setControlPointCmd->setValue(value);

            QSharedPointer<BaseCmd> sharedSetControlPointCmd(setControlPointCmd);


             SavePointXml *savePointXml =SavePointXml::getInstance();

             savePointXml->SavePointData(address,value);
             QString stata="Write-RS485";
             savePointXml->JoinSystemList(address,value,stata);
            if(DelaySendList.size()!=1)
            {
            DelaySendList.removeAt(i);
            }else
            {
               qDebug()<<"clean list now--------------------------";
                DelaySendList.clear();
                sceneListXml->setDelayTimeList(DelaySendList);
            }

            PortStruct RS485target;
            foreach (const BasePort *port , m_portList)
            {
                 if((port->portParam().type() == "UART" && port->portParam().name() == "RS485"))
                 {
                     RS485target = port->portParam();
                 }
            }
            if(RS485Port==true||ControlPortlist.size()==0)
            {
                qDebug()<<"RS485Port==true--------------------------";
                if((address > 0)||(value > 0))
                    sendCmd(RS485target,sharedSetControlPointCmd);
                else
              {

                 if(Struct.thirdFuncLen() > 0)
               emit sendDataSignal(RS485target,Struct.thirdFuncList());
              }
            }
            if(ZigbeePort==true||ControlPortlist.size()==0)
            {
            //    qDebug()<<"ZigbeePort==true--------------------------";
                ControlPointFunc *pointControlFunc = new ControlPointFunc();
                ControlPointStruct sourcePoint;
                sourcePoint.setAddress(address);
                sourcePoint.setValue(value);
                QList<ControlPointStruct> sourcePointList;
                sourcePointList.append(sourcePoint);
                pointControlFunc->setSourceDevice(this->name());
                pointControlFunc->setSourcePointList(sourcePointList);
                QSharedPointer<BaseFunc> sharedPointControlFunc(pointControlFunc);
                emit transferFuncSignal(sharedPointControlFunc);
            }

        }

    }
    if(DelaySendList.size()!=0)
    {
      sceneListXml->setDelayTimeList(DelaySendList);
    }
}

